﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Threading;
using WeighClient.Utils;
using Newtonsoft.Json.Linq;
using RabbitMQ.Client;
using WeighClient.Model;
using RabbitMQ.Client.Events;
using DotNetSpeech;
using Microsoft.WindowsAPICodePack.ApplicationServices;

namespace WeighClient.Windows
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private DispatcherTimer timer;
        private String TextProperty1 = String.Empty;

        private IModel channel = null;
        Thread readCardThread = null;

        delegate void MyDelegate(Object value);
        SynchronizationContext _syncContext = null;
        Bill bill = null;

        SpVoice speech = null;
        Thread workThread = null;

        public MainWindow()
        {
            InitializeComponent();
            _syncContext = SynchronizationContext.Current;

            DataContext = this;
            
            speech = new SpVoice();

            timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick += new EventHandler(timeCycle);
            timer.Start();

            this.Loaded += Window_Load;
            this.Unloaded += Window_UnLoad;

            RegisterForRestartRecovery();
        }
        private void Window_Load(object sender, RoutedEventArgs e)
        {
            txtDeviceCode.Text = App.GetConfig().DeviceCode;
            /*
            this.WindowState = System.Windows.WindowState.Normal;
            this.WindowStyle = System.Windows.WindowStyle.None;
            this.ResizeMode = System.Windows.ResizeMode.NoResize;
            this.Topmost = true;

            this.Left = 0.0;
            this.Top = 0.0;
            this.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
            this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
            */
            try
            {
                HttpServer server = App.GetHttpServer();
                if (null != server)
                {
                    HttpServer.sendMsgEvent += Server_sendMsgEvent;
                }

                PortControlHelper readCardCom = App.GetDeviceInfo().readCardCom;
                if (null == readCardCom)
                {
                    App.GetDeviceInfo().readCardCom = new PortControlHelper();
                    App.GetDeviceInfo().readCardCom.OnComReceiveDataHandler += Com_DataReceived;
                    readCardCom = App.GetDeviceInfo().readCardCom;
                }
                if (!readCardCom.PortState)
                {
                    readCardCom.OpenPort(App.GetConfig().IC_Card_PortName, 9600, 8, 1);
                }
                if (!"".Equals(App.GetConfig().IO_Com_PortName))
                {
                    IoComControlHelper ioCom = App.GetDeviceInfo().ioComControlHelper;
                    if (null == ioCom)
                    {
                        App.GetDeviceInfo().ioComControlHelper = new IoComControlHelper();
                        //App.GetDeviceInfo().ioComControlHelper.OnComReceiveDataHandler += IoCom_DataReceived;
                        ioCom = App.GetDeviceInfo().ioComControlHelper;
                    }
                    if (!ioCom.PortState)
                    {
                        ioCom.OpenPort(App.GetConfig().IO_Com_PortName, 19200, 8, 1);
                    }
                }

                string weightCommPortName = App.GetConfig().Weight_Comm_PortName;
                if (!"".Equals(weightCommPortName))
                {
                    WeightPortControlHelper weightComm = App.GetDeviceInfo().weightCom;
                    if (null == weightComm)
                    {
                        App.GetDeviceInfo().weightCom = new WeightPortControlHelper();
                        App.GetDeviceInfo().weightCom.OnComReceiveDataHandler += Com_Weight_DataReceived;
                        weightComm = App.GetDeviceInfo().weightCom;
                    }
                    if (!App.GetDeviceInfo().weightCom.PortState)
                    {
                        App.GetDeviceInfo().weightCom.OpenPort(App.GetConfig().Weight_Comm_PortName, 9600, 8, 1);
                    }
                }
                
                /*
                if (null == readCardThread)
                {
                    readCardThread = new Thread(AutoReadCard)
                    {
                        IsBackground = true
                    };
                    readCardThread.Start();
                }
                */

                //连接消息队列
                var factory = new ConnectionFactory();
                factory.HostName = App.GetConfig().Mq_HostName;
                factory.UserName = App.GetConfig().Mq_UserName;
                factory.Password = App.GetConfig().Mq_Password;
                var connection = factory.CreateConnection();
                channel = connection.CreateModel();

                if (App.GetConfig().AutoWeigh)
                {
                    labelAutoWeigh.Text = "自动计量";
                }
                else
                {
                    labelAutoWeigh.Text = "手动计量";
                }

                subscriptionMQ();

                sendClientAutoWeigh();

                //获取监控端操作员身份信息
                JObject jsonParamObj = new JObject();
                jsonParamObj.Add("from", "client");
                jsonParamObj.Add("clientId", App.GetConfig().DeviceCode);
                jsonParamObj.Add("type", "GetLoginUserInfo");
                SendMqMessage(jsonParamObj);

                workThread = new Thread(DoWork)
                {
                    IsBackground = true
                };
                workThread.Start();
            }
            catch(Exception ex)
            {
                LogObject.WriteLog(ex.ToString(), "Error");
                MessageBox.Show(ex.ToString());
            }
        }
        private void Window_UnLoad(object sender, RoutedEventArgs e)
        {
            App.GetRunTimeVariable().ApplicationIsRuning = false;
            if (App.GetDeviceInfo().ioComControlHelper.isOpen)
            {
                App.GetDeviceInfo().ioComControlHelper.ClosePort();
            }
        }
        private void DoWork()
        {
            if (!App.GetRunTimeVariable().ApplicationIsRuning) return;

            if (!App.GetRunTimeVariable().AutoWeigh)
            {
                Thread.Sleep(1000);
                DoWork();
                return;
            }
            int status = App.GetRunTimeVariable().Status;

            switch (status)
            {
                case (int)RunTimeVariable.Operation.CarNo:
                    //获取车牌后，开始读卡
                    //发送读卡命令
                    
                    break;
                case (int)RunTimeVariable.Operation.StartReadCard:
                    /*if (double.Parse(App.GetRunTimeVariable().Weight) >= 0.02) {
                        Thread.Sleep(2000);
                    }
                    else */if (!App.GetRunTimeVariable().WeighSteady)
                    {
                        _syncContext.Post(AddLogMessage, new LogInfo("重量不稳定", true));
                        Thread.Sleep(3000);
                    }
                    else
                    {
                        double dVal = double.Parse(App.GetRunTimeVariable().Weight);
                        if (dVal < 0.02)
                        {
                            Thread.Sleep(1000);
                        }
                        else {
                            if (!App.GetRunTimeVariable().ReadCarding)
                            {
                                _syncContext.Post(AddLogMessage, new LogInfo("开始读卡,请放置IC卡至读卡区域"));
                                Thread.Sleep(5000);

                                try
                                {
                                    App.GetDeviceInfo().readCardCom.SendHexData("FF CC 01 58 38 31 30 36 31 38 93");
                                }
                                catch (Exception ex)
                                {
                                    LogObject.WriteLog("读卡失败,"+ex.ToString(), "Error");
                                    _syncContext.Post(AddLogMessage, new LogInfo("读卡失败,请联系管理员"));
                                    Thread.Sleep(5000);
                                    App.GetRunTimeVariable().ReadCarding = false;
                                }
                                Thread.Sleep(3000);
                            }
                        }
                    }
                    break;
                case (int)RunTimeVariable.Operation.ReadCard:
                    //读卡后，开始读取重量
                    string videoCarNo = App.GetRunTimeVariable().CarNo;
                    string billCarNo = bill.carNo;
                    
                    if (App.GetRunTimeVariable().WeighSteady && App.GetRunTimeVariable().AutoWeigh)
                    {
                        //_syncContext.Post(AddLogMessage, new LogInfo("读取重量:" + App.GetRunTimeVariable().Weight + ",稳定"));
                        _syncContext.Post(AddLogMessage, new LogInfo("上传过磅信息"));
                        
                        UploadWeightInfo();
                        
                        Thread.Sleep(3000);
                    }
                    else
                    {
                        _syncContext.Post(AddLogMessage, new LogInfo("重量不稳定",true));
                        Thread.Sleep(3000);
                    }

                    break;
                case (int)RunTimeVariable.Operation.ReadingIOInput:
                    //判断是否可以抬杆
                    if (App.GetRunTimeVariable().CanOpenIoComm)
                    {
                        //执行抬杆
                        String inOpenPort = App.GetConfig().IO_In_Open_Port;
                        String outOpenPort = App.GetConfig().IO_Out_Open_Port;
                        App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(inOpenPort));
                        Thread.Sleep(2000);
                        App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(outOpenPort));

                        //
                        _syncContext.Post(SetCarNo, "");
                        _syncContext.Post(SetBillInfo, new Bill());
                        _syncContext.Post(AddLogMessage, new LogInfo("等待计量"));
                        App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.Wait;
                    }
                    else
                    {
                        App.GetDeviceInfo().ioComControlHelper.readInputs();
                    }
                    break;
            }

            Thread.Sleep(1000);

            DoWork();
        }
        private void subscriptionMQ()
        {
            var consumer = new EventingBasicConsumer(channel);//消费者

            channel.BasicConsume("Queue_" + App.GetConfig().DeviceCode + "_Server", true, consumer);//消费消息
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body.ToArray());

                JObject jsonObj = JObject.Parse(message);
                string from = (string)jsonObj.GetValue("from");
                if ("monitor".Equals(from))
                {
                    Server_sendMsgEvent(jsonObj);
                }
            };
        }

        private void Server_sendMsgEvent(Object obj)
        {
            MyDelegate d = new MyDelegate(DealMessage);
            this.Dispatcher.Invoke(d, obj);
        }
        void DealMessage(Object obj)
        {
            JObject jsonObj = JObject.Parse(obj.ToString());
            String type = (String)jsonObj.GetValue("type");

            if ("GetCarNo".Equals(type))
            {
                JObject detailObj = (JObject)jsonObj.GetValue("detail");
                String carNo = (String)detailObj.GetValue("carNo");
                String direction = (String)jsonObj.GetValue("direction");

                _syncContext.Post(SetCarNo, carNo);

                _syncContext.Post(AddLogMessage, new LogInfo("获取车号:" + carNo));

                App.GetRunTimeVariable().CarNo = carNo;
                //向集控端发送车号识别结果
                //SendCarNoToMonitor(carNo);

                //向集控端发送LED显示信息
                //SendVoiceTxtToMonitor(carNo + "请刷卡过磅", carNo + "请刷卡过磅");
                /*
                Bill bill = new Bill();
                bill.videoCarNo = carNo;
                _syncContext.Post(SetBillInfo, bill);
                */
                //App.GetRunTimeVariable().WeighComplete = false;
                App.GetRunTimeVariable().CarDirection = direction;

                //向集控端发送车牌号
                JObject jsonParamObj = new JObject();
                jsonParamObj.Add("from", "client");
                jsonParamObj.Add("clientId", App.GetConfig().DeviceCode);
                jsonParamObj.Add("type", "GetCarNo");
                jsonParamObj.Add("carNo", carNo);

                _syncContext.Post(SendMqMessage, jsonParamObj);
            }
            else if ("Weight".Equals(type))
            {
                JObject detailObj = (JObject)jsonObj.GetValue("detail");
                String weight = (String)detailObj.GetValue("weight");
                //_syncContext.Post(AddLogTxt, "重量: " + weight);

                weightChange(weight);
            }
            else if ("BillInfo".Equals(type))
            {
                JObject detailObj = (JObject)jsonObj.GetValue("detail");
                //SendBillInfoToMonitor(detailObj);
            }
            else if ("complete".Equals(type))
            {
                _syncContext.Post(SetCarNo, "");
                _syncContext.Post(SetBillInfo, new Bill());
                _syncContext.Post(AddLogMessage, new LogInfo("等待计量"));

                JObject jsonPramObj = new JObject();
                jsonPramObj.Add("from", "client");
                jsonPramObj.Add("clientId", App.GetConfig().DeviceCode);
                jsonPramObj.Add("type", "ClearBillInfo");
                jsonPramObj.Add("message", "计量完成");

                _syncContext.Post(SendMqMessage, jsonPramObj);
            }
            else if ("gateStatus".Equals(type))
            {
                String inOut = (String)jsonObj.GetValue("inOut");
                String open = (String)jsonObj.GetValue("open");

                JObject jsonPramObj = new JObject();
                jsonPramObj.Add("from", "client");
                jsonPramObj.Add("clientId", App.GetConfig().DeviceCode);
                jsonPramObj.Add("type", "gateStatus");
                jsonPramObj.Add("inOut", inOut);
                jsonPramObj.Add("open", open);

                _syncContext.Post(SendMqMessage, jsonPramObj);
            }
            else if ("AutoWeigh".Equals(type))
            {
                String autoWeigh = (String)jsonObj.GetValue("value");
                if ("true".Equals(autoWeigh))
                {
                    App.GetConfig().AutoWeigh = true;
                    labelAutoWeigh.Text = "自动计量";
                }
                else
                {
                    App.GetConfig().AutoWeigh = false;
                    labelAutoWeigh.Text = "手动计量";
                }
            }
            else if ("UploadClientAutoWeigh".Equals(type))
            {
                sendClientAutoWeigh();
            }
            else if ("ReadCard".Equals(type))
            {
                if (!App.GetRunTimeVariable().AutoWeigh)
                {
                    _syncContext.Post(AddLogMessage, new LogInfo("开始读卡,请放置IC卡至读卡区域"));
                    Thread.Sleep(3000);

                    try
                    {
                        App.GetDeviceInfo().readCardCom.SendHexData("FF CC 01 58 38 31 30 36 31 38 93");
                    }
                    catch (Exception ex)
                    {
                        LogObject.WriteLog("读卡失败1," + ex.ToString(), "Error");
                        _syncContext.Post(AddLogMessage, new LogInfo("读卡失败,请联系管理员"));
                        SendMonitorVoice("读卡失败");
                        Thread.Sleep(3000);
                    }
                }
            }
            else if ("ReadWeight".Equals(type))
            {
                if (!App.GetRunTimeVariable().AutoWeigh)
                {
                    ReadWeight();
                }
            }
            else if ("SaveWeight".Equals(type))
            {
                if (!App.GetRunTimeVariable().AutoWeigh)
                {
                    UploadWeightInfo();
                }
            }
            else if ("DealError".Equals(type))
            {
                App.GetDeviceInfo().Error = false;
                App.GetRunTimeVariable().WeighComplete = false;
                App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.Wait;
            }
            else if ("ServerOperatorInfo".Equals(type))
            {
                String loginUserID = (String)jsonObj.GetValue("loginUserId");
                String loginUserName = (String)jsonObj.GetValue("loginUserName");

                App.GetRunTimeVariable().loginUserId = loginUserID;
                App.GetRunTimeVariable().loginUserName = loginUserName;

                _syncContext.Post(AddLogMessage, new LogInfo("操作员," + loginUserName));
            }
            else if ("ChangeDoorStatus".Equals(type))
            {
                string inOut = (String)jsonObj.GetValue("inOut");
                string status = (String)jsonObj.GetValue("status");

                if ("in".Equals(inOut))
                {
                    if ("open".Equals(status))
                    {
                        App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(App.GetConfig().IO_In_Open_Port));
                    }
                    else if ("close".Equals(status))
                    {
                        App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(App.GetConfig().IO_In_Close_Port));
                    }
                }
                else if ("out".Equals(inOut))
                {
                    if ("open".Equals(status))
                    {
                        App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(App.GetConfig().IO_Out_Open_Port));
                    }
                    else if ("close".Equals(status))
                    {
                        App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(App.GetConfig().IO_Out_Close_Port));
                    }
                }
            }
            else if ("PrintSmallTicket".Equals(type))
            {
                Console.WriteLine("PrintSmallTicket...");

                JObject billObj = (JObject)jsonObj.GetValue("billObj");
                Bill bill = Json2Bill(billObj);
                
                PrintUtils.printWeighOrder(bill);
            }
        }

        private void Com_DataReceived(String response)
        {
            App.GetRunTimeVariable().ReadCarding = true;
            try
            {
                String[] resArray = ByteUtils.MySplit(response, 2);
                if (resArray.Length < 5) {
                    App.GetRunTimeVariable().ReadCarding = false;
                    return; 
                }

                if (resArray[3] == "68")
                {
                    //读GUID 32位
                    if (resArray.Length < 37) return;

                    String str = "";

                    ASCIIEncoding ASCIITochar = new ASCIIEncoding();
                    String s = "";
                    for (int i = 4; i < 36; i++)
                    {
                        s += resArray[i];
                    }
                    byte[] aa = ByteUtils.strToToHexByte(s);
                    char[] ascii = ASCIITochar.GetChars(aa);

                    for (int i = 0; i < ascii.Length; i++)
                    {
                        str += ascii[i];
                    }
                    App.GetRunTimeVariable().CardGuid = str;
                    App.GetRunTimeVariable().ReadCarding = true;
                    _syncContext.Post(AddLogMessage, new LogInfo("IC卡读取成功"));
                    Thread.Sleep(3000);

                    bill = LoadBillInfo(str);
                    if (null == bill)
                    {
                        _syncContext.Post(AddLogMessage, new LogInfo("提取单据失败", true));
                        SendMonitorVoice("提取单据失败");
                        Thread.Sleep(3000);

                        App.GetRunTimeVariable().ReadCarding = false;
                        return;
                    }
                    //向集控端发送提单信息
                    JObject jsonParamObj = new JObject();
                    jsonParamObj.Add("from", "client");
                    jsonParamObj.Add("clientId", App.GetConfig().DeviceCode);
                    jsonParamObj.Add("type", "BillInfo");
                    jsonParamObj.Add("billObj", JObject.FromObject(bill));

                    _syncContext.Post(SendMqMessage, jsonParamObj);

                    _syncContext.Post(SetBillInfo, bill);

                    App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.ReadCard;
                    App.GetRunTimeVariable().ReadCarding = false;
                }
                else
                {
                    App.GetRunTimeVariable().ReadCarding = false;
                }
            }catch(Exception ex)
            {
                LogObject.WriteLog(ex.ToString(), "Error");
                App.GetRunTimeVariable().ReadCarding = false;
            }
        }
        private void IoCom_DataReceived(String response)
        {
            String[] resArray = ByteUtils.MySplit(response, 2);
            if (resArray.Length == 15)
            {
                string direction = App.GetRunTimeVariable().CarDirection;
                int pos = 4;
                if ("in".Equals(direction))
                {
                    pos = int.Parse(App.GetConfig().IO_In_Input_Port) + 3;
                }
                else if ("out".Equals(direction))
                {
                    pos = int.Parse(App.GetConfig().IO_Out_Input_Port) + 3;
                }
                if (pos >= 4 && pos <= 7)
                {
                    if ("00".Equals(resArray[pos]))
                    {
                        Thread.Sleep(3000);
                        App.GetRunTimeVariable().CanOpenIoComm = true;
                    }
                }
            }
        }
        private void UploadWeightInfo()
        {
            App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.UploadBillInfo;
            App.GetRunTimeVariable().WeighComplete = true;

            JObject jsonParamObj = new JObject();
            string weight = App.GetDeviceInfo().Weight.ToString();

            if (App.GetRunTimeVariable().AutoWeigh)
            {
                //自动计量
                if (bill.busitype.Equals("销售"))
                {
                    double w01 = double.Parse(weight);
                    double w02 = App.GetConfig().MaxWeigh;

                    if (w01 > w02)
                    {
                        //超限
                        App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.Warning;
                        App.GetRunTimeVariable().WeighComplete = false;
                        _syncContext.Post(AddLogMessage, new LogInfo("计量失败,重量超限", true));
                        
                        jsonParamObj.Add("from", "client");
                        jsonParamObj.Add("clientId", App.GetConfig().DeviceCode);
                        jsonParamObj.Add("type", "Error");
                        jsonParamObj.Add("message", "计量失败,重量超限");
                        jsonParamObj.Add("devalue", "99");

                        _syncContext.Post(SendMqMessage, jsonParamObj);

                        return;
                    }
                }
            }
            
            JObject resultJSON = UploadBillInfo(bill.id, bill.guid, weight, bill.videoCarNo);
            string result = (string)resultJSON["result"];
            if (!"ok".Equals(result) && !"complete".Equals(result))
            {
                App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.Warning;
                App.GetRunTimeVariable().WeighComplete = false;

                string message = (string)resultJSON["message"];
                string devalue = (string)resultJSON["devalue"];
                _syncContext.Post(AddLogMessage, new LogInfo("计量失败,"+ message, true));

                jsonParamObj.Add("from", "client");
                jsonParamObj.Add("clientId", App.GetConfig().DeviceCode);
                jsonParamObj.Add("type", "Error");
                jsonParamObj.Add("message", message);
                jsonParamObj.Add("devalue", devalue);

                _syncContext.Post(SendMqMessage, jsonParamObj);
                return;
            }

            if (App.GetRunTimeVariable().AutoWeigh)
            {
                if ("1".Equals(App.GetConfig().DeviceType))
                {
                    //单向磅
                    String outOpenPort = App.GetConfig().IO_Out_Open_Port;
                    App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(outOpenPort));
                }
                else if ("2".Equals(App.GetConfig().DeviceType))
                {
                    string direction = App.GetRunTimeVariable().CarDirection;
                    if ("in".Equals(direction))
                    {
                        String inOpenPort = App.GetConfig().IO_In_Open_Port;
                        App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(inOpenPort));
                    }
                    else if ("out".Equals(direction))
                    {
                        String outOpenPort = App.GetConfig().IO_Out_Open_Port;
                        App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(outOpenPort));
                    }
                }
            }
            if ("complete".Equals(result))
            {
                String msg1 = "正在打印称重计量单,请等待";
                _syncContext.Post(AddLogMessage, new LogInfo(msg1));

                PrintUtils.printWeighOrder(bill);
            }
            string msg = "计量完成";
            _syncContext.Post(AddLogMessage, new LogInfo(msg));

            //向集控端发送计量完成
            jsonParamObj.RemoveAll();
            jsonParamObj.Add("from", "client");
            jsonParamObj.Add("clientId", App.GetConfig().DeviceCode);
            jsonParamObj.Add("type", "Complete");
            jsonParamObj.Add("message", msg);
            jsonParamObj.Add("pizhong", bill.pizhong);
            jsonParamObj.Add("maozhong", bill.maozhong);
            jsonParamObj.Add("jingzhong", bill.jingzhong);

            _syncContext.Post(SendMqMessage, jsonParamObj);
        }
        private Bill LoadBillInfo(String guid)
        {
            Bill bill = null;

            try
            {
                String bodyJsonStr = "{\"guid\":\"" + guid + "\"}";

                String serverIp = App.GetConfig().HttpServerIp;
                String serverPort = App.GetConfig().HttpServerPort;

                String result = HttpPostHelper.doHttpPost("http://"+ serverIp + ":"+ serverPort + "/ytBill/selectBillByGuid", bodyJsonStr);
                JObject resJSON = JObject.Parse(result);
                bool success = (bool)resJSON.GetValue("success");

                if (success)
                {
                    JObject detailJSON = (JObject)resJSON.GetValue("data");
                    String id = (String)detailJSON.GetValue("id");
                    String orderCode = (String)detailJSON.GetValue("billNo");
                    String carNo = (String)detailJSON.GetValue("carNumber");
                    String productName = (String)detailJSON.GetValue("productName");
                    String corpName = (String)detailJSON.GetValue("corpName");
                    String position = (String)detailJSON.GetValue("position");
                    String planNum = (String)detailJSON.GetValue("planNum");
                    String _guid = (String)detailJSON.GetValue("guid");
                    bill = new Bill();

                    bill.id = id;
                    bill.orderCode = orderCode;
                    bill.carNo = carNo;
                    bill.productName = productName;
                    bill.corpName = corpName;
                    bill.position = position;
                    bill.planNum = planNum;
                    bill.videoCarNo = App.GetRunTimeVariable().CarNo;

                    bill.weightStatus = (String)detailJSON.GetValue("weightStatus");
                    bill.yuanfaNum = (String)detailJSON.GetValue("yuanfaNum");
                    bill.chazhi = (String)detailJSON.GetValue("chazhi");
                    bill.fayou = (String)detailJSON.GetValue("fayou");
                    bill.pizhong = (String)detailJSON.GetValue("pizhong");
                    bill.maozhong = (String)detailJSON.GetValue("maozhong");
                    bill.jingzhong = (String)detailJSON.GetValue("jingzhong");
                    bill.qianbiao = (String)detailJSON.GetValue("qianbiao");
                    bill.houbiao = (String)detailJSON.GetValue("houbiao");
                    bill.busitype = (String)detailJSON.GetValue("busitype");
                    bill.operatorName = "";

                    bill.guid = _guid;
                }
            }
            catch (Exception ex)
            {
                bill = null;
                LogObject.WriteLog("加载单据为空," + ex.ToString(), "Error");
            }

            return bill;
        }
        private bool ReadWeight()
        {
            bool interrupt = App.GetDeviceInfo().WeightInterrupt;
            bool comlete = false;
            bool readCardSuccess = App.GetDeviceInfo().ReadCardSuccess;
            if (!readCardSuccess) return false;

            while (!interrupt && !comlete && readCardSuccess)
            {
                //该线程会进行无限循环，自己不会结束
                bool isSteady = App.GetDeviceInfo().isSteady(10);
                if (isSteady)
                {
                    _syncContext.Post(AddLogMessage, new LogInfo("获取重量: " + App.GetDeviceInfo().Weight));

                    comlete = true;
                    return true;
                }
                else
                {
                    _syncContext.Post(AddLogMessage, new LogInfo("重量不稳定", true));
                    Thread.Sleep(1000);
                    interrupt = App.GetDeviceInfo().WeightInterrupt;
                    readCardSuccess = App.GetDeviceInfo().ReadCardSuccess;
                }
            }
            return false;
        }
        private JObject UploadBillInfo(String id, String guid, String weight, string carNo)
        {
            JObject resultJSON = new JObject();
            try
            {
                //String bodyJsonStr = "{\"position\":\"" + id + "\",\"guid\":\"" + guid + "\",\"weight\":\"" + weight + "\"}";
                JObject paramObj = new JObject();
                paramObj.Add("position", id);
                paramObj.Add("guid", guid);
                paramObj.Add("weight", weight);
                paramObj.Add("carNumber", carNo);
                paramObj.Add("operatorId", App.GetRunTimeVariable().loginUserId);
                paramObj.Add("operatorName", App.GetRunTimeVariable().loginUserName);
                bill.operatorName = App.GetRunTimeVariable().loginUserName;

                String bodyJsonStr = paramObj.ToString();

                String serverIp = App.GetConfig().HttpServerIp;
                String serverPort = App.GetConfig().HttpServerPort;
                String result = HttpPostHelper.doHttpPost("http://"+ serverIp + ":"+ serverPort + "/ytBill/tareByGuid", bodyJsonStr);
                JObject resJSON = JObject.Parse(result);
                string status = (string)resJSON.GetValue("status");

                if ("success".Equals(status))
                {
                    //App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.UploadBillInfo;
                    string jltype = (string)resJSON.GetValue("jltype");
                    if ("2".Equals(jltype))
                    {
                        if (bill.busitype.Equals("销售"))
                        {
                            bill.maozhong = weight;
                            _syncContext.Post(SetMaoWeight, weight);
                        }
                        else if (bill.busitype.Equals("采购"))
                        {
                            bill.pizhong = weight;
                            _syncContext.Post(SetPiWeight, weight);
                        }
                        double jingzhong = double.Parse(bill.maozhong) - double.Parse(bill.pizhong);
                        bill.jingzhong = jingzhong.ToString("0.00");
                        _syncContext.Post(SetJingWeight, bill.jingzhong);

                        resultJSON.Add("result", "complete");
                        return resultJSON;
                    }
                    if (bill.busitype.Equals("销售"))
                    {
                        bill.pizhong = weight;
                        _syncContext.Post(SetPiWeight, weight);
                    }
                    else if (bill.busitype.Equals("采购"))
                    {
                        bill.maozhong = weight;
                        _syncContext.Post(SetMaoWeight, weight);
                    }
                    resultJSON.Add("result", "ok");
                    return resultJSON;
                }
                string message = (string)resJSON.GetValue("message");
                string devalue = (string)resJSON.GetValue("devalue");

                //App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.Warning;
                //
                resultJSON.Add("result", "error");
                resultJSON.Add("message", message);
                resultJSON.Add("devalue", devalue);
                return resultJSON;
            }
            catch (Exception ex)
            {
                LogObject.WriteLog("上传数据异常," + ex.ToString(), "Error");
                resultJSON.Add("result", "error");
                resultJSON.Add("message", "系统异常");
                resultJSON.Add("devalue", "-1");
                return resultJSON;
            }
        }
        private void SetBillInfo(Object obj)
        {
            Bill billObj = (Bill)obj;
            this.txtBillCode.Text = billObj.orderCode;
            this.txtProductName.Text = billObj.productName;
            this.txtPiZhong.Text = billObj.pizhong;
            this.txtMaoZhong.Text = billObj.maozhong;
            this.txtJingZhong.Text = billObj.jingzhong;

            this.txtCorpName.Text = billObj.corpName;
            this.txtPosition.Text = billObj.loadPlace;

            this.txtPlanNum.Text = billObj.planNum;
            this.txtCarNo.Text = billObj.carNo;
            this.txtVideoCarNo.Text = billObj.videoCarNo;

            JObject jsonObj = JObject.FromObject(billObj);
        }
        private void AddLogMessage(Object obj)
        {
            LogInfo log = (LogInfo)obj;
            this.txtLog.Text = log.message;
            if (log.waring)
            {
                this.txtLog.Foreground = Brushes.Red;
                LogObject.WriteLog(log.message, "Error");
            }
            else
            {
                this.txtLog.Foreground = Brushes.LightGreen;
                LogObject.WriteLog(log.message);
            }
            speak(this.txtLog.Text);
        }

        private void SendMqMessage(Object obj)
        {
            JObject jsonObj = (JObject)obj;

            if (null != channel)
            {
                var properties = channel.CreateBasicProperties();
                properties.DeliveryMode = 1;

                string message = jsonObj.ToString();

                channel.BasicPublish("", "Queue_" + App.GetConfig().DeviceCode + "_Client", properties, Encoding.UTF8.GetBytes(message));
            }
        }
        private void SetCarNo(object text)
        {
            this.txtCarNo.Text = text.ToString();
        }
        private void SetWeight(object text)
        {
            this.txtWeight.Text = text.ToString();
            bool isSteady = App.GetDeviceInfo().isSteady(App.GetConfig().SteadySeconds);
            App.GetRunTimeVariable().Weight = text.ToString();
            App.GetRunTimeVariable().WeighSteady = isSteady;
            if (!isSteady)
            {
                this.txtWeight.Foreground = Brushes.Red;
            }
            else
            {
                this.txtWeight.Foreground = Brushes.LightGreen;
            }
        }

        private void SetPiWeight(object val)
        {
            txtPiZhong.Text = (string)val;
        }
        private void SetMaoWeight(object val)
        {
            txtMaoZhong.Text = (string)val;
        }
        private void SetJingWeight(object val)
        {
            txtJingZhong.Text = (string)val;
        }
        public void timeCycle(object sender, EventArgs e)
        {
            new Thread(() =>
            {
                Application.Current.Dispatcher.BeginInvoke(
                    new Action(() =>
                    {
                        TextProperty1 = DateTime.Now.ToString();
                        this.labelTime.Text = TextProperty1;
                    }));
            }).Start();
        }

        private void Img_Click(object sender, MouseButtonEventArgs e)
        {
            PassWindow win = new PassWindow();
            bool result = (bool)win.ShowDialog();
            if (result)
            {
                this.Close();
            }
        }

        private void speak(String message)
        {
            try
            {
                speech.Speak(string.Empty, SpeechVoiceSpeakFlags.SVSFPurgeBeforeSpeak);
                if (null != message)
                {
                    speech.Speak(message, SpeechVoiceSpeakFlags.SVSFlagsAsync);
                }
            }catch(Exception ex) { }
        }

        private void sendClientAutoWeigh()
        {
            JObject jsonObj = new JObject();
            jsonObj.Add("from", "client");
            jsonObj.Add("clientId", App.GetConfig().DeviceCode);
            jsonObj.Add("type", "UploadClientAutoWeigh");

            string _autoWeigh = "false";
            if (App.GetConfig().AutoWeigh)
            {
                _autoWeigh = "true";
            }
            else
            {
                _autoWeigh = "false";
            }
            jsonObj.Add("value", _autoWeigh);

            _syncContext.Post(SendMqMessage, jsonObj);
        }

        private void Com_Weight_DataReceived(String response)
        {
            try
            {
                string valStr = response.Substring(10, 8);
                valStr = valStr.Substring(1, 1) + valStr.Substring(3, 1) + "." + valStr.Substring(5, 1) + valStr.Substring(7, 1);
                double dblVal = double.Parse(valStr);
                string weight = dblVal.ToString("00.00");
                App.GetDeviceInfo().Weight = dblVal;
                weightChange(weight);
            }
            catch(Exception ex)
            {
                _syncContext.Post(AddLogMessage, new LogInfo("获取重量异常", true));
            }
        }
        public void weightChange(string weight)
        {
            //return;
            _syncContext.Post(SetWeight, weight);

            //向集控端发送实时重量
            bool isSteady = App.GetDeviceInfo().isSteady(App.GetConfig().SteadySeconds);
            String strSteady = "不稳定";
            if (isSteady)
            {
                strSteady = "稳定";
            }

            JObject jsonParamObj = new JObject();
            jsonParamObj.Add("from", "client");
            jsonParamObj.Add("clientId", App.GetConfig().DeviceCode);
            jsonParamObj.Add("type", "Weight");
            jsonParamObj.Add("weight", weight);
            jsonParamObj.Add("steady", strSteady);

            _syncContext.Post(SendMqMessage, jsonParamObj);


            bool complete = App.GetRunTimeVariable().WeighComplete;
            RunTimeVariable runTimeVariable = App.GetRunTimeVariable();
            if (isSteady && double.Parse(weight) >= 0.02
                && !complete
                && App.GetRunTimeVariable().Status == (int)RunTimeVariable.Operation.Wait
                && !App.GetRunTimeVariable().ReadCarding
                && App.GetRunTimeVariable().CarNo != ""
                )
            {
                if (App.GetRunTimeVariable().AutoWeigh)
                {
                    //开始读卡
                    App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.StartReadCard;
                }
            }
            else if (double.Parse(weight) == 0 && App.GetRunTimeVariable().Status != (int)RunTimeVariable.Operation.Wait) //isSteady && 
            {
                /*
                JObject jsonPramObj = new JObject();
                jsonPramObj.Add("from", "client");
                jsonPramObj.Add("clientId", App.GetConfig().DeviceCode);
                jsonPramObj.Add("type", "Complete");
                jsonPramObj.Add("message", "计量完成");

                _syncContext.Post(SendMqMessage, jsonPramObj);
                */
                App.GetRunTimeVariable().WeighComplete = false;
                App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.Wait;
                App.GetRunTimeVariable().ReadCarding = false;
                App.GetRunTimeVariable().BillId = "";
                App.GetRunTimeVariable().CarNo = "";

                if ("1".Equals(App.GetConfig().DeviceType))
                {
                    //地磅清零
                    _syncContext.Post(SetCarNo, "");
                    _syncContext.Post(SetBillInfo, new Bill());
                    _syncContext.Post(AddLogMessage, new LogInfo("等待计量"));
                    App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.Wait;
                    //单向磅
                    String inOpenPort = App.GetConfig().IO_In_Open_Port;
                    App.GetDeviceInfo().ioComControlHelper.openDoor(int.Parse(inOpenPort));

                    //发送清空
                    JObject jsonPramObj = new JObject();
                    jsonPramObj.Add("from", "client");
                    jsonPramObj.Add("clientId", App.GetConfig().DeviceCode);
                    jsonPramObj.Add("type", "ClearBillInfo");
                    jsonPramObj.Add("message", "计量完成");

                    _syncContext.Post(SendMqMessage, jsonPramObj);
                }
                else if ("2".Equals(App.GetConfig().DeviceType))
                {
                    //地磅清零
                    //_syncContext.Post(SetCarNo, "");
                    //_syncContext.Post(SetBillInfo, new Bill());
                    _syncContext.Post(AddLogMessage, new LogInfo("等待下磅"));

                    //双向磅,读取车检器状态
                    App.GetRunTimeVariable().CanOpenIoComm = false;
                    App.GetRunTimeVariable().Status = (int)RunTimeVariable.Operation.ReadingIOInput;
                    App.GetDeviceInfo().ioComControlHelper.readInputs();
                }
            }
        }
        private void SendMonitorVoice(string message)
        {
            //向集控端发送语音
            JObject jsonParamObj = new JObject();
            jsonParamObj.Add("from", "client");
            jsonParamObj.Add("clientId", App.GetConfig().DeviceCode);
            jsonParamObj.Add("type", "VoiceAndLed");
            jsonParamObj.Add("message", message);

            _syncContext.Post(SendMqMessage, jsonParamObj);
        }
        private void ImgLogo_Click(object sender, MouseButtonEventArgs e)
        {
            PassWindow win = new PassWindow();
            bool result = (bool)win.ShowDialog();
            if (result)
            {
                this.Close();
            }
        }

        private void RegisterForRestartRecovery()
        {
            RestartSettings restartSettings = new RestartSettings("restart",
                RestartRestrictions.NotOnReboot | RestartRestrictions.NotOnPatch);
            ApplicationRestartRecoveryManager.RegisterForApplicationRestart(restartSettings);

            RecoveryData data = new RecoveryData(new RecoveryCallback(PerformRecovery), null);
            RecoverySettings recoverySettings = new RecoverySettings(data, 0);
            ApplicationRestartRecoveryManager.RegisterForApplicationRecovery(recoverySettings);
        }
        private void UnRegisterRestartRecovery()
        {
            ApplicationRestartRecoveryManager.UnregisterApplicationRestart();
            ApplicationRestartRecoveryManager.UnregisterApplicationRecovery();
        }
        private int PerformRecovery(object state)
        {
            bool isCanceled = ApplicationRestartRecoveryManager.ApplicationRecoveryInProgress();
            if (isCanceled)
            {
                ApplicationRestartRecoveryManager.ApplicationRecoveryFinished(false);
            }

            //recovery your work here ...
            ApplicationRestartRecoveryManager.ApplicationRecoveryFinished(true);
            return 0;
        }

        Bill Json2Bill(JObject detailJSON)
        {
            String id = (String)detailJSON.GetValue("id");
            String orderCode = (String)detailJSON.GetValue("billNo");
            String carNo = (String)detailJSON.GetValue("carNumber");
            String productName = (String)detailJSON.GetValue("productName");
            String corpName = (String)detailJSON.GetValue("corpName");
            String position = (String)detailJSON.GetValue("position");
            String planNum = (String)detailJSON.GetValue("planNum");
            String _guid = (String)detailJSON.GetValue("guid");
            Bill bill = new Bill();

            bill.id = id;
            bill.orderCode = orderCode;
            bill.carNo = carNo;
            bill.productName = productName;
            bill.corpName = corpName;
            bill.position = position;
            bill.planNum = planNum;
            bill.videoCarNo = App.GetRunTimeVariable().CarNo;

            bill.weightStatus = (String)detailJSON.GetValue("weightStatus");
            bill.yuanfaNum = (String)detailJSON.GetValue("yuanfaNum");
            bill.chazhi = (String)detailJSON.GetValue("chazhi");
            bill.fayou = (String)detailJSON.GetValue("fayou");
            bill.pizhong = (String)detailJSON.GetValue("pizhong");
            bill.maozhong = (String)detailJSON.GetValue("maozhong");
            bill.jingzhong = (String)detailJSON.GetValue("jingzhong");
            bill.qianbiao = (String)detailJSON.GetValue("qianbiao");
            bill.houbiao = (String)detailJSON.GetValue("houbiao");
            bill.busitype = (String)detailJSON.GetValue("busitype");
            bill.operatorName = (String)detailJSON.GetValue("operatorName");
            bill.print = (String)detailJSON.GetValue("print");
            bill.guid = _guid;

            return bill;
        }
    }
}
